﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LRT.Nebula.Xml;
using LRT.Syndication.Components;
using System.Net;
using System.Xml;

namespace LRT.Syndication.Business
{
    public static class RSSFeedVisitor
    {
        public static Channel GetChannel(XmlDocument rss) 
        {

            var channel = rss.SelectSingleNode("rss/channel[1]");
            return DeserializeChannel(channel);
            
        }

        public static IEnumerable<Item> GetItems(XmlDocument rss)
        {
            var items = rss.SelectNodes("rss/channel/item");
            var list = new List<Item>();
            foreach (XmlNode item in items)
            {
                list.Add(DeserializeItem(item));
            }
            return list;
        }

        static Channel DeserializeChannel(XmlNode channelNode)
        {
            var title = channelNode.SelectSingleNode("title");
            var link = channelNode.SelectSingleNode("link");
            var description = channelNode.SelectSingleNode("description");
            return new Channel() { Title = title == null ? String.Empty : title.InnerText,
                                   Link = link == null ? String.Empty : link.InnerText,
                                   Description = description == null ? String.Empty : description.InnerText
                                 };
        }

        static Item DeserializeItem(XmlNode itemNode)
        {
            var title = itemNode.SelectSingleNode("title");
            var link = itemNode.SelectSingleNode("link");
            var description = itemNode.SelectSingleNode("description");
            return new Item()
            {
                Title = title == null ? String.Empty : title.InnerText,
                Link = link == null ? String.Empty : link.InnerText,
                Description = description == null ? String.Empty : description.InnerText
            };
        }


        public static RSS GetRSS(string url)
        {
            var client = new WebClient();
            var str = client.DownloadString(url);
            return XmlHelper.Deserialize<RSS>(str);
        }


    }
}
